import React, { useState, useEffect } from 'react';
import { LeftOutlined, RightOutlined } from '@ant-design/icons';
import { MyPaginationStyled } from './style';

type MyPaginationPropsType = {
  total: number;
  pageChange: (curPage: number) => void;
};

const MyPagination: React.FC<MyPaginationPropsType> = (props) => {
  const [curPage, setCurPage] = useState<number>(1);
  const [totalPage, setTotalPage] = useState<number>(0);
  const [isAllowClick, setIsAllowClick] = useState<{ left: boolean; right: boolean }>({ left: true, right: true });

  useEffect(() => {
    // 向上取整
    setTotalPage(Math.ceil(props.total / 8));
  }, [props.total]);

  useEffect(() => {
    props.pageChange(curPage);
  }, [curPage]);

  // 根据当前页和总页数判断是否可以点击
  useEffect(() => {
    let allowClick = {
      left: true,
      right: true,
    };
    if (curPage <= 1) {
      allowClick.left = false;
    }
    if (curPage >= totalPage) {
      allowClick.right = false;
    }
    setIsAllowClick(allowClick);
  }, [curPage, totalPage]);

  // 分页左点击
  const clickLeftPage = () => {
    if (curPage > 1) {
      setCurPage(curPage - 1);
    }
  };
  // 分页右点击
  const clickRightPage = () => {
    if (curPage < totalPage) {
      setCurPage(curPage + 1);
    }
  };
  return (
    <MyPaginationStyled isAllowClick={isAllowClick}>
      <span className='left-page' onClick={clickLeftPage}>
        <LeftOutlined />
      </span>
      {curPage}/{totalPage}
      <span className='right-page' onClick={clickRightPage}>
        <RightOutlined />
      </span>
    </MyPaginationStyled>
  );
};

export default MyPagination;
